package com.example.yue.zxinglibrarytest;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import banding.com.google.Zxing.exceptions.FileCanNotReadException;
import banding.com.google.Zxing.utils.BitmapUtil;

/**
 * @author Yue
 * @date 2017/8/4 13:58
 */
public class ImagesActivity extends Activity implements OnClickListener {
    private Bitmap bitmap;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_images);
        assignViews();
    }

    private void assignViews() {
        findViewById(R.id.btn_load_images).setOnClickListener(this);
        int m = (int) (10000 * 10000 * 4 / 1024d / 1024d);
        ((TextView) findViewById(R.id.tv_load_images)).setText("图片占用内存大小：像数*位深/8 \n 10240*10240，配置ARGB_8888，无压缩时占用内存400M，配置ARGB_4444，无压缩时占用内存300M ");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_load_images:
                String path = Environment.getExternalStorageDirectory().toString() + "/test.png";
                try {
                    //只适合普通场合使用。
                    bitmap = BitmapUtil.loadBitmap(path);
                } catch (FileCanNotReadException e) {
                    e.printStackTrace();
                }
                if (bitmap == null) {
                    return;
                }
                Log.d(">>>","bitmap,w="+bitmap.getWidth()+" h="+bitmap.getHeight());
                BitmapDrawable bd = new BitmapDrawable(getResources(), bitmap);
                Log.d(">>>","bitmap,w="+bd.getIntrinsicWidth()+" mw="+bd.getMinimumWidth());
                findViewById(R.id.rootLayout_images).setBackgroundDrawable(bd);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //图片太大，不自己释放，可能会挂掉
        if (bitmap!=null) {
            bitmap.recycle();
        }
        long free =Runtime.getRuntime().freeMemory();
        long limit = Runtime.getRuntime().maxMemory()/8;
        Log.d(">>>","free:"+free/1024+"kb "+limit/1024+"kb");
        if (free < limit){
            System.gc();
        }
    }
}
